package com.robot.common.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES实现手机号加密、解密
 */
public class AESEncryptionUtils {

    // 临时写死的固定密钥（实际使用中，应该从安全的地方获取密钥，而不是硬编码）
    private static final String KEY = "5T8B4Q2W9X6C3V7A1E4K9P2Z8D6S7MNB"; // 必须是16（AES-128）, 24（AES-192）, 或 32（AES-256）字节长

    private static final String ALGORITHM = "AES";
    private static final String ALGORITHM_NAME = "AES/ECB/PKCS5Padding";

    private static final int KEY_SIZE = 128;


    /**
     * 临时根据固定Key值生成密钥
     * @return
     * @throws Exception
     */
    public static SecretKey generateKeyTemporary()  {
        // 初始化密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        return secretKeySpec;


    }


    // 生成AES密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE, new SecureRandom());
        return keyGenerator.generateKey();
    }

    // 加密
    public static String encrypt(String content, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedContent, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] originalBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedContent));
        return new String(originalBytes);
    }




}
